package cn.bistu.cs.music.Service;

import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.Nullable;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import cn.bistu.cs.music.gson.MusicId2Url;
import cn.bistu.cs.music.util.HttpUtil;
import cn.bistu.cs.music.util.Utility;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class DownloadService extends IntentService {
    public DownloadService() {
        super("This is DownloadService for music!");
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        Bundle bundle = intent.getExtras();
        String downloadUrl = bundle.getString("download_url");
        String musicName = bundle.getString("musicName");
        final String[] url = {null};
        HttpUtil.sendOkHttpRequest(downloadUrl, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                MusicId2Url musicId2Url = Utility.handleMusicId2UrlResponse(response);
                url[0] = musicId2Url.getData().get(0).getUrl();
                Log.e("下载启动：", downloadUrl);
                //文件保存地址,把音乐下载到/storage/.../Download中 Environment.getExternalStorageDirectory().getAbsolutePath()
                File dirs = new File("/storage/11E9-130A/Music/");
                if (!dirs.exists()) {// 检查文件夹是否存在，不存在则创建
                    dirs.mkdir();
                }
                //输出文件名
                File file = new File(dirs, musicName+".mp3");
                //开始下载

                if(url[0]!=null&&!"".equals(url[0])){
                    downloadFile(url[0],file);
                }
                else {
                    Looper.prepare();
                    Toast.makeText(getApplicationContext(), "暂无资源，请选择其他音频！", Toast.LENGTH_LONG).show();
                    Looper.loop();
                }
                Log.e("下载:","结束");
            }
        });
    }

    private void downloadFile(String downloadUrl, File file) {
        Log.e("url:=",downloadUrl);
        FileOutputStream _outputStream;//文件输出流
        try {
            _outputStream = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            Log.e("找不到目标文件", "找不到目录！");
            e.printStackTrace();
            return;
        }
        InputStream _inputStream = null;//文件输入流
        try {
            URL url = new URL(downloadUrl);
            HttpURLConnection _downLoadCon = (HttpURLConnection) url.openConnection();
            _downLoadCon.setRequestMethod("GET");
            _inputStream = _downLoadCon.getInputStream();
            Log.e("返回流",""+_inputStream);
            int respondCode = _downLoadCon.getResponseCode();//服务器返回的响应码
            if (respondCode == 200) {
                byte[] buffer = new byte[1024*8];// 数据块，等下把读取到的数据储存在这个数组，这个东西的大小看需要定，不要太小。
                int len;
                while ((len = _inputStream.read(buffer)) != -1) {
                    _outputStream.write(buffer, 0, len);
                }
            } else {
                Log.e("服务器返回为空：", "respondCode:" + respondCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {//别忘了关闭流
                if (_outputStream != null) {
                    _outputStream.close();
                }
                if (_inputStream != null) {
                    _inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}